// 发布会议
<template>
  <layoutDividerPage class="kick-off">
    <template #search>
      <div class="button-list">
        <el-button type="primary" @click="submitForm">确认提交</el-button>
      </div>
    </template>
    <el-form
      ref="formRef"
      class="form"
      :model="formData"
      :rules="formRules"
      status-icon
      label-position="right"
      label-width="100"
    >
      <el-col :span="6">
        <el-form-item label="会议主题：" prop="meetingTopic">
          <el-input
            v-model="formData.meetingTopic"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="会议时间：" prop="meetingTime">
          <el-date-picker
            v-model="formData.meetingTime"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm"
            time-format="HH:mm"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="会议地点：" prop="location">
          <el-input
            v-model="formData.location"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-col>
      <el-form-item label="参会人：" prop="participantIds">
        <el-select
          v-model="formData.participantIds"
          multiple
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in participantInfo"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会议描述：" prop="description">
        <el-input
          v-model="formData.description"
          placeholder="请输入"
          type="textarea"
          :rows="5"
          clearable
        />
      </el-form-item>
      <el-col :span="6">
        <el-form-item label="会议类型：" prop="meetingType">
          <el-select
            v-model="formData.meetingType"
            placeholder="请选择"
            disabled
          >
            <el-option
              v-for="item in _discStore.getDictType('meeting_type')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-form-item label="关联信息：" required>
        <el-table :data="formData.associations" border>
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="类型">
            <template #default="scope">
              <el-form-item
                :prop="`associations.${scope.$index}.associationType`"
                :rules="formRules.associations[0].fields.associationType"
              >
                <el-select
                  v-if="scope.row.isEditing"
                  v-model="scope.row.associationType"
                  placeholder="请选择"
                  :disabled="scope.row.isDisabled"
                  clearable
                  @change="handleAssociationByType"
                >
                  <el-option
                    v-for="item in _discStore.getDictType(
                      'meeting_association_type'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>
                  {{
                    _discStore.getDictLabelForValue(
                      'meeting_association_type',
                      scope.row.associationType
                    )
                  }}
                </span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="内容">
            <template #default="scope">
              <el-form-item
                :prop="`associations.${scope.$index}.associationValue`"
                :rules="formRules.associations[0].fields.associationValue"
              >
                <el-select-v2
                  v-if="scope.row.isEditing"
                  v-model="scope.row.associationValue"
                  filterable
                  clearable
                  :options="
                    associationContentMap.get(scope.row.associationType) || []
                  "
                  value-key="associationId"
                  placeholder="请选择"
                  :disabled="scope.row.isDisabled"
                />
                <span v-else>
                  {{ scope.row.associationValue.associationContent }}
                </span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!isSkipMeeting" label="操作" width="160">
            <template #default="scope">
              <el-button type="danger" link @click="removeItem(scope.$index)">
                删除
              </el-button>
              <el-button
                v-if="isEditPage && !scope.row.isEditing"
                type="primary"
                link
                @click="toggleEdit(scope.row)"
              >
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item v-if="!isSkipMeeting">
        <el-button type="primary" plain @click="addItem">
          <el-icon class="el-icon--left"><CirclePlus /></el-icon>
          增加关联信息
        </el-button>
      </el-form-item>
    </el-form>
  </layoutDividerPage>
</template>

<script lang="ts" setup>
  import dayjs from 'dayjs'
  import type { FormInstance, FormRules, FormItemRule } from 'element-plus'
  import layoutDividerPage from '@/components/layoutDividerPage.vue'
  import {
    formKickoffProps,
    resCreateProps,
    userSimpleProps,
    resUserSimpleProps,
    resDetailsProps,
    resAssociationTypeProps,
    associationsReportProps,
  } from '../interface'

  import {
    getMeetingsCreate,
    getMeetingsDetails,
    getMeetingsGetAssociationByType,
    getMeetingsUpdate,
  } from '@/api/project/meeting'
  import { getAllUser } from '@/api/system/user'

  import { useDictStore } from '@/store/modules/dict'
  import { useTimeFormat } from '@/utils/useTimeFormat'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'

  const route = useRoute()

  const { closeTabNavigate } = useCloseTabNavigate()
  const _discStore = useDictStore()
  const { updateTime } = useTimeFormat()

  const formRef = ref<FormInstance>()
  const formData = reactive<Partial<formKickoffProps>>({
    // 由会议管理里面发起会议 默认为临时会议
    meetingType: 'TEMP_MEETING',
    participantIds: [],
    associations: [],
  })

  const requiredRule = (message: string) => ({
    required: true,
    message,
    trigger: 'blur',
  })

  const formRules = reactive<FormRules<formKickoffProps>>({
    meetingTopic: [requiredRule('请输入会议主题')],
    meetingTime: [requiredRule('请选择会议时间')],
    location: [requiredRule('请输入会议地点')],
    participantIds: [
      {
        type: 'array',
        required: true,
        message: '请选择参会人',
        trigger: 'change',
      },
    ],
    description: [requiredRule('请输入会议描述')],
    meetingType: [requiredRule('请选择会议类型')],
    associations: [
      {
        type: 'array',
        required: true,
        message: '关联信息不能为空',
        trigger: 'blur',
        fields: {
          associationType: {
            type: 'string',
            required: true,
            message: '请选择类型',
            trigger: 'blur',
          } as FormItemRule,
          associationValue: {
            type: 'object', // 修改为对象类型
            required: true,
            message: '请选择内容',
            trigger: 'blur',
            fields: {
              associationId: {
                type: 'number',
                required: true,
                message: '请选择内容',
                trigger: 'blur',
              },
              associationContent: {
                type: 'string',
                required: true,
                message: '请选择内容',
                trigger: 'blur',
              },
            },
          } as FormItemRule,
        },
      },
    ],
  })

  // 人员信息
  const participantInfo = ref<userSimpleProps[]>([])
  // 关联信息变量
  const associationContentMap = ref<Map<string, any[]>>(new Map())
  // 由其他路由进入发起的会议 需屏蔽一些操作
  const isSkipMeeting = ref<boolean>(false)
  // 是否编辑会议页面  是直接在会议详情里面直接进入编辑状态
  const isEditPage = ref<boolean>(false)
  const handleAssociationByType = async (type: string) => {
    try {
      const params = {
        associationType: type,
      }
      const res: resAssociationTypeProps =
        await getMeetingsGetAssociationByType(params)
      if (res && res.code === 0 && res.data) {
        const mappedData = res.data.map((item) => {
          return {
            value: {
              associationContent: item.associationContent,
              associationId: item.associationId,
            },
            label: item.associationContent,
          }
        })
        associationContentMap.value.set(type, mappedData)
      } else {
        ElMessage.error(`获取关联信息失败: ${res.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('获取关联信息失败', e)
    }
  }
  // 添加关联信息
  const addItem = () => {
    formData.associations.push({
      associationValue: {
        associationId: '',
        associationContent: '',
      },
      associationType: '',
      isEditing: true,
    })
  }

  // 移除关联信息
  const removeItem = (index: number) => {
    formData.associations.splice(index, 1)
  }

  // 切换编辑状态
  const toggleEdit = (row: associationsReportProps) => {
    row.isEditing = !row.isEditing
    handleAssociationByType(row.associationType)
  }

  // 确认提交
  const submitForm = async () => {
    const valid = await formRef.value.validate()
    if (!valid) return

    if (
      formData.associations.length === 0 &&
      formData.meetingType !== 'TEMP_MEETING'
    ) {
      ElMessage.error('关联信息不能为空')
      return
    }
    console.log('submitForm', formData)
    try {
      const { meetingTime, ...otherParams } = formData
      const startTime = new Date(meetingTime[0])
      const endTime = new Date(meetingTime[1])
      const timeDiff = endTime.getTime() - startTime.getTime()
      const minutesDiff = timeDiff / (1000 * 60)
      const tempAssociation = formData.associations.map((item) => {
        return {
          associationType: item.associationType,
          associationId: item.associationValue.associationId,
          associationContent: item.associationValue.associationContent,
        }
      })

      if (!isEditPage.value) {
        const params = {
          ...otherParams,
          estimatedDuration: minutesDiff,
          startTime: updateTime(startTime),
          associations: tempAssociation,
        }
        console.log('params', params)
        const res: resCreateProps = await getMeetingsCreate(params)
        if (res && res.code === 0) {
          ElMessage.success('发布会议成功')
          closeTabNavigate({ name: 'Meetings_List' })
        } else {
          ElMessage.error(`发布会议失败: ${res.msg || '未知错误'}`)
        }
      } else {
        const params = {
          ...otherParams,
          estimatedDuration: minutesDiff,
          startTime: updateTime(startTime),
          associations: tempAssociation,
          id: route.query?.id || '',
        }
        console.log('params', params)
        const res: resCreateProps = await getMeetingsUpdate(params)
        if (res && res.code === 0) {
          ElMessage.success('编辑会议成功')
          closeTabNavigate({ name: 'Meetings_List' })
        } else {
          ElMessage.error(`编辑会议失败: ${res.msg || '未知错误'}`)
        }
      }
    } catch (e) {
      console.error('交易失败', e)
    }
  }
  // 获取人员信息
  const getUserInfoList = async () => {
    try {
      const res: resUserSimpleProps = await getAllUser()
      if (res && res.code === 0) {
        participantInfo.value = res.data || []
      }
    } catch (e) {
      console.error('获取人员信息失败', e)
    }
  }

  onMounted(() => {
    getUserInfoList()
  })

  // 查询明细
  const handleSearchDetails = async (id: string) => {
    try {
      const res: resDetailsProps = await getMeetingsDetails({ id })
      if (!res || !res.data) {
        console.error('未获取到会议明细数据')
        formRef.value.resetFields()
        return
      }

      const {
        startTime,
        estimatedDuration,
        participants,
        meetingTopic,
        location,
        description,
        meetingType,
        associations,
      } = res.data

      const startDayjs = dayjs(startTime || null)
      const endDayjs = startDayjs.add(estimatedDuration || 0, 'minute')

      const startTimeFormatted = startDayjs.isValid()
        ? startDayjs.format('YYYY-MM-DD HH:mm')
        : ''
      const endTimeFormatted = endDayjs.isValid()
        ? endDayjs.format('YYYY-MM-DD HH:mm')
        : ''

      const participantIds = participants
        ? participants.map((item) => item.participantId)
        : []

      const tempAssociation = associations.map((item) => {
        return {
          associationValue: {
            associationContent: item.associationContent,
            associationId: item.associationId,
          },
          associationType: item.associationType,
        }
      })
      Object.assign(formData, {
        meetingTopic: meetingTopic || '',
        meetingTime: [startTimeFormatted, endTimeFormatted],
        location: location || '',
        description: description || '',
        meetingType: meetingType || '',
        participantIds: participantIds,
        associations: tempAssociation,
      })
    } catch (e) {
      console.error('查询会议明细异常', e)
      // Object.assign(formData, {})
      formRef.value.resetFields()
    }
  }

  // 监听路由变换
  watch(
    () => route.query,
    (newQuery) => {
      const { id, associationId, associationType, meetingType } = newQuery

      if (id) {
        handleSearchDetails(id as string)
        isEditPage.value = true
      }

      if (associationId && associationType && meetingType) {
        formData.meetingType = meetingType as string
        isSkipMeeting.value = true
        handleAssociationByType(associationType as string).then(() => {
          const selectedOption = associationContentMap.value
            .get(associationType as string)
            .find((option) => option.value.associationId === associationId)
          const newAssociation = {
            associationType: associationType as string,
            associationValue: {
              associationId: associationId as string,
              associationContent: selectedOption.label,
            },
            isEditing: false, // 新增的关联信息不处于编辑状态
          }
          formData.associations.push(newAssociation)
        })
      }
    },
    { immediate: true }
  )
</script>

<style lang="scss" scoped>
  .kick-off {
    .button-list {
      display: flex;
      align-items: center;
      justify-content: end;
      margin: 20px;
    }
    .form {
      width: 100%;
      padding: 20px;
    }

    :deep(.el-table) {
      .el-form-item {
        margin-bottom: 0;
      }
      .el-form-item__error {
        position: static;
        white-space: nowrap;
      }
    }
  }
</style>
